package com.hmall.search.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.dto.SearchDTO;
import com.hmall.common.pojo.Item;
import com.hmall.common.vo.SearchVO;
import com.hmall.search.mapper.ItemMapper;
import com.hmall.search.service.ISearchService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
/**
 * @Author: dai
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class SearchService extends ServiceImpl<ItemMapper, Item> implements ISearchService {
    private final ItemMapper itemMapper;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public SearchVO filter(SearchDTO searchDTO) {
        LambdaQueryWrapper<Item> categoryWrapper = Wrappers.<Item>lambdaQuery()
                .select(Item::getCategory)
                .groupBy(Item::getCategory);

        LambdaQueryWrapper<Item> brandWrapper = Wrappers.<Item>lambdaQuery()
                .select(Item::getBrand)
                .groupBy(Item::getBrand);

        List<String> category = list(categoryWrapper).stream().map(Item::getCategory).collect(Collectors.toList());
        List<String> brand = list(brandWrapper).stream().map(Item::getBrand).collect(Collectors.toList());
        return SearchVO.builder()
                .category(category)
                .brand(brand)
                .build();
    }

    @Override
    public PageDTO<Item> listWithCondition(SearchDTO searchDTO) {
        PageHelper.startPage(searchDTO.getPage(), searchDTO.getSize());
        if (searchDTO.getMinPrice() != null && searchDTO.getMaxPrice() != null) {
            searchDTO.setMinPrice(searchDTO.getMinPrice() * 100);
            searchDTO.setMaxPrice(searchDTO.getMaxPrice() * 100);
        }
        Page<Item> page = itemMapper.page(searchDTO);

        return PageDTO.<Item>builder()
                .total(page.getTotal())
                .list(page.getResult())
                .build();
    }
    @RabbitListener(queues = "item.id")
    public void clearCache(String itemId) {
        if (StrUtil.isNotEmpty(itemId)) {
            stringRedisTemplate.delete("hot:item:top20");
        }
    }
}
